//
//  LYNetworkTools.swift
//  Swift网络请求封装
//
//  Created by liuerying on 16/5/22.
//  Copyright © 2016年 liuerying. All rights reserved.
//

import UIKit

import AFNetworking

enum HTTPMethdos:Int {
    case POST
    case GET
}

struct API {
    static let hostName = "https://api.weibo.com/"
    //加载用户token值
    static let loadAccessToken = "oauth2/access_token"
   //加载用户信息
    static let loasUserInfo = "2/users/show.json"
    //加载首页数据
    static let loadHomePageData = "statuses/home_timeline.json"
    
    //加载用户发布微博的数据
    static let loadSendStatus = "2/statuses/update.json"
    
    //发布图片的借口
    static let sendImageStatus = "https://upload.api.weibo.com/2/statuses/upload.json"
}

//声明单例对象
class LYNetworkTools: AFHTTPSessionManager {
    static let sharedTools:LYNetworkTools = {
    
        let url = NSURL(string: API.hostName)
        let tools = LYNetworkTools(baseURL: url)
        //添加模式
    tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
  
        return tools
    }()






func request(method: HTTPMethdos,urlString: String,parameters: AnyObject?,finished:(responseObject:AnyObject?,error: NSError?)->()){

    //定义闭包参数,
    let succes = {(task:NSURLSessionDataTask,result:AnyObject?)->() in
    //执行请求成功的回调
        finished(responseObject: result, error:nil)
    }
    
    let failure = {(task:NSURLSessionDataTask?,error:NSError?)->() in
    finished(responseObject: nil, error: error)
        print(error)
        
        
    }
    
    if method == .GET{
    
        GET(urlString, parameters: parameters, progress: nil, success: succes, failure: failure)


    }else{
    
//        POST(urlString, parameters: parameters, progress: nil, success: succes, failure: failure)

    
        POST(urlString, parameters: parameters, progress: nil, success: succes, failure: failure)
    }
    
}
}


extension LYNetworkTools{

    ///请求用户的token
    func loadAccessToken(code: String,finished:(responseObject: AnyObject?,error:NSError?)->()){
    //拿到接口
    //设置参数(从文档中获取)
    let paramers = ["client_id" : client_id ,"client_secret" : client_secret ,"grant_type" : "authorization_code","code" : code,"redirect_uri" : redirect_uri]
    
        //调用核心的封装请求数据的方法
        request(.POST, urlString: API.loadAccessToken, parameters: paramers, finished: finished)
        
    }
    
    
    ///加载用户信息
    func loadUserInfo(response: [String: AnyObject] ,finished:(responseObject:AnyObject?,error: NSError?)->()){

        //用户访问接口权限的标识
    let token = response["access_token"]!
    
    let uid = response["uid"]!
    
    
    let paramerters = ["access_token" : token, "uid" : uid]
    

        request(.GET, urlString: API.loasUserInfo, parameters: paramerters, finished: finished)
}


}

//加载首页数据
extension LYNetworkTools{

    func loadHomePageData(since_id:Int64,max_id:Int64, finished:(responseObject:AnyObject?,error: NSError?)->()){
    
        guard let token = LYUserAccountModel.sharedAccountViewModel.userAccount?.access_token else{
        
            return
        }
        
        var parameters = ["access_token":token]
        //如果大于0 ,添加参数
        if since_id > 0 {
        
            parameters["since_id"] = "\(since_id)"
            
        }
        
        if max_id>0{
        
            parameters["max_id"] = "\(max_id)"
        }
        
        request(.GET, urlString: API.loadHomePageData, parameters: parameters, finished: finished)
    }
}


//发布文本 & 发布图片 的 微博的数据
extension LYNetworkTools{

    func sendStatus(status:String,images:[UIImage], finished:(responseObject:AnyObject?,error: NSError?)->()){
    
        guard let token = LYUserAccountModel.sharedAccountViewModel.userAccount?.access_token else{
            return
        }
        let parameters = ["access_token": token,"status":status]
        
        //当有图片的时候
        if images.count > 0 {
  
            
            self.POST(API.sendImageStatus, parameters: parameters, constructingBodyWithBlock: { (formData) in
                
                //将上传的二进制数据添加到formdata中
                for image in images{
                    
                    let imageData = UIImagePNGRepresentation(image)!
                    formData.appendPartWithFileData(imageData, name: "pic", fileName: "ad", mimeType: "application/octet-stream")
                    
                }
                
                }, progress: nil, success: { (_, result) in
                    
                    finished(responseObject: result, error: nil)
                    
                }, failure: { (_, error) in
                    
                    finished(responseObject: nil, error: error)
            })
            

            
            
            
        }else{
        
            //发布文本微博
        request(.POST, urlString: API.loadSendStatus, parameters: parameters, finished: finished)

        }
    }
    
}




















